import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess, customResponse } from '~/utils/response';
import { type mysqlOkPacket, queryDatabase } from '~/functions';

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  try {
    let queryString;
    const args = [];
    // 读取GET请求的参数
    const { action, data } = await readBody(event);
    if (!action || !data) throw new Error('请求参数不完整！');
    // 解析data参数为数组，并将sampleName字段转为JSON字符串，避免其为数组导致数据库操作报错
    const cloneData = JSON.parse(data);
    cloneData.sampleName = JSON.stringify(cloneData.sampleName);

    if (action === 'delete') {
      // 解析data参数为数组
      const sampleNoList = cloneData.map((item) => item);
      queryString = `DELETE FROM samplelists WHERE sampleNo IN (?)`;
      const res = <mysqlOkPacket>await queryDatabase(queryString, [sampleNoList]);
      return useResponseSuccess({
        code: res.affectedRows === sampleNoList.length ? 0 : 1,
        msg:
          res.affectedRows === sampleNoList.length
            ? '删除成功！'
            : `共${sampleNoList.length}条，仅删除${res.affectedRows}条！`,
      });
    } else if (action === 'insert') {
      // 新增或另存，处理编号

      const queryDate = cloneData.receiveDate;
      const [year, month] = queryDate.split('-').map(Number); // 获取年月
      const yearMonth = year.toString() + month.toString().padStart(2, '0');
      // 查询:
      // 前一个：同月内 <= queryDate 的最大sampleNo
      // 后一个：同月内 > queryDate 的最小receiveDate的最小sampleNo
      queryString = `
        (
          SELECT DATE_FORMAT(receiveDate, '%Y-%m-%d') AS receiveDate, sampleNo FROM samplelists WHERE receiveDate <= ? AND DATE_FORMAT(receiveDate, '%Y%m') = ?
          ORDER BY sampleNo DESC
          LIMIT 1
        )
        UNION ALL
        (
          SELECT DATE_FORMAT(receiveDate, '%Y-%m-%d') AS receiveDate, sampleNo FROM samplelists WHERE receiveDate > ? AND DATE_FORMAT(receiveDate, '%Y%m') = ?
          ORDER BY receiveDate ASC, sampleNo ASC
          LIMIT 1
        )
      `;

      const results = <any[]>await queryDatabase(queryString, [queryDate, yearMonth, queryDate, yearMonth]);

      // 生成sampleNo、reportNo的前后缀
      let codePrefix = 'RT/JC-YP-' + year + month.toString().padStart(2, '0');
      let codeSuffix;

      if (results.length === 0) {
        // 情况1：当月无样品
        codeSuffix = 1;
      } else if (results.length === 1) {
        const resSampleNo = parseInt(results[0].sampleNo.split('-').pop(), 10);
        const resReceiveDate = results[0].receiveDate.replace(/-/g, '');

        if (parseInt(resReceiveDate, 10) <= parseInt(queryDate.replace(/-/g, ''), 10)) {
          // 情况2：当前收样时间晚于当月的所有，其实需要判断sampleNo是否是9999，再+1
          codeSuffix = resSampleNo + 1;
        } else {
          // 情况3：当前收样时间早于当月的所有，需要判断sampleNo是否是0001，是则报错，否则取1
          if (resSampleNo === 1) {
            throw new Error('当前样品期望0001编号，但已存在，请调整收样时间！');
          } else if (resSampleNo > 1) {
            codeSuffix = 1;
          }
        }
      } else if (results.length === 2) {
        // 判断是否连续，如果是连续的，抛出错误，否则取前一个sampleNo+1
        const prevSampleNo = parseInt(results[0].sampleNo.split('-').pop(), 10);
        const nextSampleNo = parseInt(results[1].sampleNo.split('-').pop(), 10);
        if (nextSampleNo - prevSampleNo > 1) {
          // 情况4：当前收样时间位于中间，需要插入，且存在空余编号
          codeSuffix = prevSampleNo + 1;
        } else if (nextSampleNo - prevSampleNo === 1) {
          // 情况5：当前收样时间位于中间，但无空余编号，需要调整收样时间
          throw new Error('当前收样时间需插入，但无空余编号，请调整收样时间！');
        }
      } else {
        throw new Error('数据库查询结果不符合预期！');
      }
      // 判断codeSuffix是否为数字且大于0
      if (isNaN(codeSuffix) || codeSuffix <= 0) {
        throw new Error('样品编号生成失败！');
      }
      cloneData.sampleNo = codePrefix + '-' + codeSuffix.toString().padStart(4, '0');
      cloneData.reportNo = codePrefix.replace('RT/JC-YP-', 'RT/JC-') + '-' + codeSuffix.toString().padStart(3, '0');
    }

    // 插入数据库,如果存在则更新

    const fields = Object.keys(cloneData).join(', ');
    const placeholders = Object.keys(cloneData)
      .map(() => '?')
      .join(', ');
    queryString = `INSERT INTO samplelists (${fields}) VALUES (${placeholders})
          ON DUPLICATE KEY UPDATE ${Object.keys(cloneData)
            .map((k) => `${k}=VALUES(${k})`)
            .join(', ')}`;

    await queryDatabase(queryString, [...Object.values(cloneData)]);
    return useResponseSuccess('提交成功！');
  } catch (error) {
    return customResponse(-2, error.message);
  }
});
